# -*- coding: utf-8 -*-
import os
import wsgiref.handlers
import struct
import time
import urllib
import logging
from StringIO import StringIO
from google.appengine.api import urlfetch
from google.appengine.api import images
from models import *

def save_image_from_url(url, max_width=480, max_height=550):
    try:
        image_data =urlfetch.fetch(url, allow_truncated=True).content
    except:
        return

    if not image_data:
        return
        
    if len(image_data) > 3000*1024:
            self.error(400)
            return self.response.out.write('图像太大了...')

    content_type, width, height = getImageInfo(image_data)

    if not content_type == 'image/png' and not content_type == 'image/jpeg' and not content_type == 'image/gif':
        return

    image_data = images.resize(image_data, max_width, max_height)
    image_entity = Image(mime=content_type, data=db.Blob(image_data),width=width, height=height)
    image_entity.put()
    return image_entity.key()

                            
def getImageInfo(data):
        data = str(data)
        size = len(data)
        height = -1
        width = -1
        content_type = 'unknown content type'
        # handle GIFs
        if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'):
                # Check to see if content_type is correct
                content_type = 'image/gif'
                w, h = struct.unpack("<HH", data[6:10])
                width = int(w)
                height = int(h)
        # See PNG 2. Edition spec (http://www.w3.org/TR/PNG/)
        # Bytes 0-7 are below, 4-byte chunk length, then 'IHDR'
        # and finally the 4-byte width, height
        elif ((size >= 24) and data.startswith('\211PNG\r\n\032\n')
                    and (data[12:16] == 'IHDR')):
                content_type = 'image/png'
                w, h = struct.unpack(">LL", data[16:24])
                width = int(w)
                height = int(h)
        # Maybe this is for an older PNG version.
        elif (size >= 16) and data.startswith('\211PNG\r\n\032\n'):
                # Check to see if we have the right content type
                content_type = 'image/png'
                w, h = struct.unpack(">LL", data[8:16])
                width = int(w)
                height = int(h)
        # handle JPEGs
        elif (size >= 2) and data.startswith('\377\330'):
                content_type = 'image/jpeg'
                jpeg = StringIO(data)
                jpeg.read(2)
                b = jpeg.read(1)
                try:
                        while (b and ord(b) != 0xDA):
                                while (ord(b) != 0xFF): b = jpeg.read
                                while (ord(b) == 0xFF): b = jpeg.read(1)
                                if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
                                        jpeg.read(3)
                                        h, w = struct.unpack(">HH", jpeg.read(4))
                                        break
                                else:
                                        jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
                                b = jpeg.read(1)
                        width = int(w)
                        height = int(h)
                except struct.error:
                        pass
                except ValueError:
                        pass
        return content_type, width, height

def set_trace():
    import pdb, sys
    debugger = pdb.Pdb(stdin=sys.__stdin__,
        stdout=sys.__stdout__)
    debugger.set_trace(sys._getframe().f_back)
    #debugger.set_trace()

#cookie helper functions
def set_cookie(response, dict):
        for name in dict:
            response.headers.add_header('Set-Cookie', '%s=%s; expires=Fri, 31-Dec-2120 23:59:59 GMT'%(name, dict[name]))

def get_cookie(request, name):
        import Cookie
        cookie = Cookie.SimpleCookie(request.headers.get('Cookie'))
        return cookie[name]


class Paginator():
    def __init__(self, q, items_per_page, page=1):
        self._object_list = []
        self._has_prev = False
        self._has_next = False
        self._total_page = q.count()/items_per_page +1
        self._current_page = int(page)
        self._html = ''

        if q.count() > 0:
            self._object_list = q.fetch(items_per_page, (page-1) * items_per_page)

            next = q.fetch(1, ((page-1) * items_per_page) + len(self._object_list) )

            if next:
            	self._has_next = True

            if page > 1:
            	self._has_prev = True
        if self._has_prev:
    		self._html=self._html+'<a href="/?page='+str(self._current_page-1)+'">上一页</a> '
    	self._html=self._html+"第"+str(self._current_page)+"页, 一共"+str(self._total_page)+"页 "
    	if self._has_next:
    		self._html=self._html+'<a href="/?page='+str(self._current_page+1)+'">下一页</a>'

    def object_list(self):
        return self._object_list;

    def has_next(self):
        return self._has_next

    def has_prev(self):
        return self._has_prev

    def total_page(self):
    	return self._total_page

    def current_page(self):
    	return self._current_page

    def html(self):
    	return self._html
